<?php
namespace app\index\controller;

use app\index\model\User;
use app\index\validate\UserValidate;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Session;
use think\Request;

class Login extends Controller
{
    /**
     * 登录页面遍历
     * @return mixed
     */
    public function login()
    {
        $show = Cookie::get("errorCount") >= 3 ? true : false;
        $this->assign("show",$show);
        return $this->fetch();
    }

    /**
     * 登录操作
     * @param Request $request
     * @return \think\response\Json
     */
    public function loginUser(Request $request)
    {
        if ($request->isAjax() && $request->isPost()) {
            $ip = $request->ip();
            $scene = Cache::get($ip . "login");
            if ($scene === false) {
                //接收
                $data = $request->post();
                //dump($data);die;
                //验证
                $validate = new UserValidate();
                if (!$validate->scene("login")->check($data)) {
                    $count = Cookie::get("errorCount") ?? Cookie::set("errorCount",1);
                    $count = intval($count);
                    if ($count >= 4) {
                        Cache::set($ip . "login","true",20);
                    }
                    if (Cookie::get("errorCount") > 0) {
                        Cookie::set("errorCount",++$count);
                    }
                    $show = Cookie::get("errorCount") >= 3 ? true : false;
                    return json(["code" => 404 , "message" => $validate->getError() , "token" => $request->token() , "show" => $show]);
                    //return json(["code" => 404 , "message" => $validate->getError() , "token" => $request->token()]);
                }

                //修改最后登录IP和最后登录时间
                User::updateIp($data);
                //处理
                Cookie::delete("errorCount");
                User::login($validate->userData["id"]);
                Session::set("userInfo",$validate->userData);
                Cookie::set("userId",$validate->userData["id"]);

                $userInfo = User::getUserInfo($validate->userData["id"]);
                Session::set("userClass" . Cookie::get("userId"),$userInfo);
                return json(["code" => 1 , "message" => "登录成功"]);
            }
            return json(["code" => 404 , "message" => "错误次数过多,请五分钟后再次重试"]);
        } else {
            $this->error("页面不存在",url("Login/login"),"",0);
        }
    }

    /**
     * 退出登录
     */
    public function quitLogin()
    {
        Session::delete("userInfo");
        Cookie::delete("userId");
        $this->success("退出成功",url("Index/login/login"),"",0);
    }
}
